package org.smart4j.framework.helper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.smart4j.framework.bean.FormParam;
import org.smart4j.framework.bean.Param;
import org.smart4j.framework.util.ArrayUtil;
import org.smart4j.framework.util.CodecUtil;
import org.smart4j.framework.util.StreamUtil;
import org.smart4j.framework.util.StringUtil;


/**
 * description: 请求助手类
 * @version v1.0
 * @author w
 * @date 2018年10月24日下午5:28:56
 */
public class RequestHelper {
	
	/**
	 * description: 创建请求对象
	 * @param request
	 * @return Param
	 * @throws IOException
	 * @version v1.0
	 * @author w
	 * @date 2018年10月24日 下午5:30:57
	 */
	public static Param createParam(HttpServletRequest request) throws IOException{
		List<FormParam> formParamList = new ArrayList<>();
		formParamList.addAll(parseParamterNames(request));
		formParamList.addAll(parseInputStream(request));
		return new Param(formParamList);
	}

	private static List<FormParam>  parseParamterNames(HttpServletRequest request) {
		List<FormParam> formParamList = new ArrayList<>();
		Enumeration<String> parameterNames = request.getParameterNames();
		while(parameterNames.hasMoreElements()){
			String fieldName = parameterNames.nextElement();
			String[] fieldValues = request.getParameterValues(fieldName);
			if(ArrayUtil.isNotEmpty(fieldValues)){
				Object fieldValue;
				if(fieldValues.length == 1){
					fieldValue = fieldValues[0];
				}else{
					StringBuilder sb  = new StringBuilder("");
					for (int i = 0; i < fieldValues.length; i++) {
						sb.append(fieldValues[i]);
						if(i != fieldValues.length - 1){
							// 没到最后一个元素，添加分隔符
							sb.append(StringUtil.SEPARATOR);
						}
					}
					fieldValue = sb.toString();
				}
				formParamList.add(new FormParam(fieldName, fieldValue));
			}
		}
		return formParamList;
	} // end parseParamterNames
	
	private static List<FormParam>  parseInputStream(HttpServletRequest request) throws IOException{
		List<FormParam> formParamList = new ArrayList<>();
		// TODO: decodeURL 需检查代码 -- CodecUtil
		String body = CodecUtil.decode(StreamUtil.getString(request.getInputStream()));
		if(StringUtil.isNotEmpty(body)){
			// example: body---> name=jack&age=18&lovely
			String[] kvs = StringUtil.splitString(body, "&");
			if(ArrayUtil.isNotEmpty(kvs)){
				for (String kv : kvs) {
					String[] array = StringUtil.splitString(kv, "=");
					if(ArrayUtil.isNotEmpty(array) && array.length == 2){
						String fieldName = array[0];
						String fieldValue = array[1];
						formParamList.add(new FormParam(fieldName, fieldValue));
					}
				}
			}
		}
		return formParamList;
	}

	
}
